package com.example.api.controller.app;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.example.api.constant.BookConst;
import com.example.api.exception.ParamException;
import com.example.api.pojo.Book;
import com.example.api.service.BookService;
import com.example.api.utils.Result;
import com.example.api.utils.StringUtil;
import com.example.api.vo.BookVO;
import com.example.api.websocket.WebSocketServer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.example.api.exception.BusException;
import com.example.api.properties.AliPayProperties;
import com.example.api.utils.JSONUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping
public class PayController {

    @Resource
    AliPayProperties aliPayProperties;

    @Resource
    BookService bookService;

    @Resource
    WebSocketServer webSocketServer;

    @GetMapping("/app/pay")
    public Result<String> payAli(String num, String payWay) {

        //TODO 判断是否超时


        //TODO 参数校验
        if (StringUtil.isEmpty(num) || StringUtil.isEmpty(payWay)) {
            throw new ParamException("支付参数不能为空");
        }

        if (!"wx".equals(payWay) && !"zfb".equals(payWay)) {
            throw new ParamException("支付参数异常");
        }


        BookVO bookVO = bookService.findByNum(num);
        if (bookVO == null) {
            throw new ParamException("订单参数异常");
        }

        //订单状态
        byte status = bookVO.getStatus();
        if (status != BookConst.PENDING_PAYMENT) {
            throw new ParamException("订单参数异常");
        }

        if (payWay.equals("zfb")) {
            AlipayClient alipayClient = new
                    DefaultAlipayClient(aliPayProperties.getGatewayUrl(), aliPayProperties.getAppId(), aliPayProperties.getMerchantPrivateKey(),
                    "json", "utf-8", aliPayProperties.getAlipayPublicKey(), aliPayProperties.getSignType());

            AlipayTradeWapPayRequest alipayRequest = new AlipayTradeWapPayRequest();//创建API对应的request

            alipayRequest.setReturnUrl(aliPayProperties.getReturnUrl());
            alipayRequest.setNotifyUrl(aliPayProperties.getNotifyUrl());

            //通过num，查找订单信息
            Book order = bookService.findOrderByNum(num);

            //准备参数信息
            Map<String, Object> payParam = new HashMap<>();

            String productName = "testproduct"; //测试商品
            BigDecimal amount = order.getAmount(); //支付金额


            payParam.put("out_trade_no", num);
            payParam.put("total_amount", amount);

            payParam.put("subject", productName);
            payParam.put("timeout_express", aliPayProperties.getTimeout());
            payParam.put("product_code", "QUICK_WAP_PAY");


            try {
                String payParamInfo = JSONUtil.mapToJson(payParam);

                alipayRequest.setBizContent(payParamInfo);

                //向支付宝服务器发请求
                String result = alipayClient.pageExecute(alipayRequest).getBody();

                return Result.ok("success", result);
            } catch (JsonProcessingException | AlipayApiException e) {
                e.printStackTrace();
                throw new BusException("支付失败");
            }
        } else if ("wx".equals(payWay)) {
            return Result.ok("成功", "successWX");
        } else {
            throw new ParamException("支付方式参数异常");
        }

    }

    //通知
    //当手机端支付成功之后,支付宝服务器会调用该地址,告诉指定订单支付成功，那么这里接口就要处理相关的业务逻辑
    //比如:设置订单支付状态

    @PostMapping("/pay/alipay/notify")
    public String aliWapPay(HttpServletRequest request) throws UnsupportedEncodingException {
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
        }

        System.err.println(params);

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, aliPayProperties.getAlipayPublicKey(), aliPayProperties.getCharset(), aliPayProperties.getSignType());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (signVerified) {//验证成功
            //商户订单号
            //String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");

            String num = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            //String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");

            System.out.println("交易状态........." + trade_status);
            if (trade_status.equals("TRADE_SUCCESS")) {
                BookVO bookVO = bookService.findByNum(num);
                //订单状态
                byte status = bookVO.getStatus();
                if (status == BookConst.PENDING_PAYMENT) {

                    Map<String, String> map = new HashMap<>();
                    map.put("type", "createBook");
                    map.put("num",num);

                    String data = null;
                    try {
                        data = JSONUtil.mapToJson(map);
                        webSocketServer.sendToClient("110", data);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                    //判断该笔订单是否在商户网站中已经做过处理
                    //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                    //如果有做过处理，不执行商户的业务程序

                    //注意：
                    //付款完成后，支付宝系统发送该交易状态通知

                    //   修改数据库中out_trade_no订单的支付状态为已经支付

                    bookService.updatePaySuccess(num, "zfb");
                }
                return "success";
            } else if (trade_status.equals("TRADE_FINISHED")) {
                return "success";
            } else {
                return "fail";
            }
        } else {//验证失败
            return "fail";
            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }

        //——请在这里编写您的程序（以上代码仅作参考）——

    }


}
